import { defineStore } from 'pinia'
import axios from 'axios'

// 解析 JWT token 的函數
function parseJwt(token) {
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
    return JSON.parse(jsonPayload)
  } catch (error) {
    console.error('解析 token 失敗:', error)
    return null
  }
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    username: localStorage.getItem('username') || '',
    userId: localStorage.getItem('userId') || ''
  }),

  getters: {
    isLoggedIn: (state) => !!state.token
  },

  actions: {
    async login(username, password) {
      try {
        console.log('開始登錄請求...')
        const response = await axios.post('/auth/login', {
          username,
          password
        })
        console.log('登錄響應數據:', response.data)
        
        const { token } = response.data
        
        // 解析 token 獲取 userId
        const decodedToken = parseJwt(token)
        console.log('解析的 token 數據:', decodedToken)
        
        if (!decodedToken || !decodedToken.userId) {
          throw new Error('無效的 token 格式')
        }
        
        this.token = token
        this.username = username
        this.userId = decodedToken.userId.toString()
        
        // 保存到 localStorage
        localStorage.setItem('token', token)
        localStorage.setItem('username', username)
        localStorage.setItem('userId', this.userId)
        
        // 設置 axios 默認 header
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        console.log('設置的 Authorization header:', axios.defaults.headers.common['Authorization'])
        
        return true
      } catch (error) {
        console.error('登錄失敗:', error.response?.data || error.message)
        return false
      }
    },

    async register(username, password) {
      try {
        const response = await axios.post('/auth/register', {
          username,
          password
        })
        return true
      } catch (error) {
        console.error('註冊失敗:', error)
        return false
      }
    },

    logout() {
      // 清除狀態
      this.token = ''
      this.username = ''
      this.userId = ''
      
      // 清除 localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('userId')
      
      // 清除 axios 默認 header
      delete axios.defaults.headers.common['Authorization']
    },

    // 初始化時從 localStorage 恢復狀態
    initialize() {
      const token = localStorage.getItem('token')
      if (token) {
        this.token = token
        this.username = localStorage.getItem('username')
        this.userId = localStorage.getItem('userId')
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
      }
    }
  }
}) 